
import Promise from 'bluebird';
import jquery from 'jquery';
var $ = jquery.noConflict();
let util = {};

util.invokeServer = function (ajaxConfig, serverUrl) {
    var reqConfig = {};
    for (var key in ajaxConfig) {
        if (ajaxConfig.hasOwnProperty(key)) {
            reqConfig[key] = ajaxConfig[key];
        }
    }

    var url = ajaxConfig.path;
    if (url.length > 0 && url.charAt(0) != '/') {
        url = '/' + url;
    }
    if (serverUrl) {
        reqConfig.url = serverUrl + url;
    } else {
        reqConfig.url = window.$rootUrl + url;
    }

    var params = ajaxConfig.params || {};
    var queryStrs = [];
    for (let key in params) {
        if (params.hasOwnProperty(key)) {
            var element = params[key];
            queryStrs.push(key + '=' + element);
        }
    }
    var str = queryStrs.join('&');
    if (str) {
        reqConfig.url = reqConfig.url + '?' + str;
    }
    return new Promise((resolve, reject) => {
        reqConfig.success = (data, textStatus, response) => {
            resolve(data, textStatus, response);
        };
        reqConfig.error = (XMLHttpRequest, textStatus, errorThrown) => {
            if (XMLHttpRequest.status == 401) { //没有权限则跳到登录界面
                vbus.$emit("access-unauthorized");
                return;
            }
            reject(XMLHttpRequest, textStatus, errorThrown);
        };
        reqConfig.timeout = 300000;
        $.ajax(reqConfig);
    });
}





export default util;